import 'package:flutter/material.dart';
import 'package:tdesign_flutter/tdesign_flutter.dart';
import '/database/categray.dart';
import '/routers/fluro_navigator.dart';
import '/util/toast_utils.dart';

class CategrayCreatePage extends StatefulWidget {
  const CategrayCreatePage({super.key});

  @override
  State<StatefulWidget> createState() => _CategrayCreatePageState();
}

class _CategrayCreatePageState extends State<CategrayCreatePage>
    with SingleTickerProviderStateMixin {
  late TextEditingController nameController;
  late TextEditingController iconController;

  CategrayType? type;
  String name = '';
  String icon = '';

  @override
  void initState() {
    super.initState();

    nameController = TextEditingController();
    iconController = TextEditingController();
  }

  @override
  void dispose() {
    super.dispose();
    nameController.dispose();
    iconController.dispose();
  }

  @override
  Widget build(BuildContext context) {
    double formWidth = MediaQuery.of(context).size.width - 50;

    var args = ModalRoute.of(context)!.settings.arguments as Map;

    //! 只能赋值一次，不然无法更改
    type ??= args['type'] ?? CategrayType.income;

    void goBack() {
      NavigatorUtils.goBackWithParams(context, {'success': true});
    }

    return Scaffold(
      appBar: TDNavBar(
        useDefaultBack: false,
        leftBarItems: [
          TDNavBarItem(icon: TDIcons.close, iconSize: 24, action: goBack)
        ],
        title: '新增分类',
        height: 50,
      ),
      body: Container(
          padding: const EdgeInsets.all(10),
          color: Colors.white,
          child: Column(
            children: [
              Expanded(
                  child: SizedBox(
                width: double.infinity,
                child: Card(
                  child: Column(
                    children: [
                      const SizedBox(
                        height: 20,
                      ),
                      TDRadioGroup(
                        selectId: type!.value,
                        cardMode: true,
                        direction: Axis.horizontal,
                        directionalTdRadios:
                            List.generate(CategrayType.values.length, (index) {
                          return TDRadio(
                            id: CategrayType.values[index].value,
                            title: CategrayType.values[index].label,
                            cardMode: true,
                          );
                        }),
                        onRadioGroupChange: (selectedId) {
                          debugPrint('selectedId: $selectedId');
                          // 更新类型
                          setState(() {
                            type = CategrayType.values.firstWhere(
                                (element) => element.value == selectedId);
                          });
                        },
                      ),
                      const SizedBox(
                        height: 10,
                      ),
                      TDInput(
                        controller: nameController,
                        leftLabel: '名称：',
                        leftLabelStyle: const TextStyle(color: Colors.grey),
                        hintText: '请输入分类名称',
                        type: TDInputType.cardStyle,
                        width: formWidth,
                        inputType: TextInputType.number,
                        required: true,
                        additionInfo: name.isEmpty ? '请输入分类名称' : '',
                        additionInfoColor: Colors.red,
                        onChanged: (value) {
                          setState(() {
                            name = value;
                          });
                        },
                        onClearTap: () {
                          setState(() {
                            name = '';
                            nameController.text = name;
                          });
                        },
                      ),
                      const SizedBox(
                        height: 10,
                      ),
                      TDInput(
                        controller: iconController,
                        leftLabel: 'icon：',
                        leftLabelStyle: const TextStyle(color: Colors.grey),
                        hintText: '请输入 icon(emoji)',
                        type: TDInputType.cardStyle,
                        width: formWidth,
                        onChanged: (value) {
                          setState(() {
                            icon = value;
                          });
                        },
                        onClearTap: () {
                          setState(() {
                            icon = '';
                            iconController.text = icon;
                          });
                        },
                      ),
                      const SizedBox(
                        height: 20,
                      ),
                      TDButton(
                        text: '新增分类',
                        theme: TDButtonTheme.primary,
                        type: TDButtonType.fill,
                        width: formWidth,
                        onTap: () async {
                          debugPrint('add categray: $type $icon $name');
                          if (name.isEmpty) {
                            Toast.show('分类名称不能为空');
                            return;
                          }

                          try {
                            await DataBaseCategray.addCategray(
                                ICategray(name: name, type: type!, icon: icon));

                            Toast.show('分类新增成功！');
                            goBack();
                          } catch (e) {
                            Toast.show('分类新增失败！');
                            debugPrint('add categray error: $e');
                          }
                        },
                      )
                    ],
                  ),
                ),
              )),
            ],
          )),
    );
  }
}
